package common

import (
	"fmt"

	"gddgame.cc/galaxy/asteroid"
	"gddgame.cc/galaxy/asteroid/cluster"
	"gddgame.cc/galaxy/binocle"
	"gddgame.cc/galaxy/satellite/formula/comet"
	"gddgame.cc/galaxy/utils/def"
)

const (
	CONTROL_SERVICE = "controlService"
)

const (
	_ comet.DE = iota
	SetControl
	GetControl
)

type ControlInstance struct {
	Subject string
}

// 提供不同主体的功能定义服务
// 主体申请的服务，可以连接到该服务获取设置信息
type ControlService struct {
	def.Logger

	binocle.Service
}

func (cs *ControlService) ID() string {
	return CONTROL_SERVICE
}

func (cs *ControlService) Master(node cluster.Node) {

}

func (cs *ControlService) Init(node cluster.Node) {
	token := node.Token()

	instance := &ControlInstance{
		Subject: token,
	}
	node.SetInstance(instance)
	node.SetConfig(cluster.ThreadSafe, true)
	node.On(cluster.JoinEvent, func(message asteroid.Message) {
		message.Response(true)
	})
	node.On(cluster.LeaveEvent, func(message asteroid.Message) {
		message.Response(true)
	})
	// 提供获取配置，更新配置的接口
	node.On(SetControl, func(message asteroid.Message) {

	})

	node.On(GetControl, func(message asteroid.Message) {

	})
}
func (cs *ControlService) InitClient(client *cluster.Client) {
	client.Filter(asteroid.DefaultFilter, func(message asteroid.Message, member def.Member) {
		switch socket := member.(*cluster.SocketInstance).Instance().(type) {
		case ControlListen:
			fmt.Println(socket)
		}
	})
}
func (cs *ControlService) CloseInstance(node cluster.Node) {
	//fmt.Println("close chess block", node.Token())
}
func (cs *ControlService) CloseClient(client *cluster.Client) {

}

type ControlClient struct {
	*cluster.Client
}

type ControlListen interface {
}

func NewControlClient(container cluster.Container, subject string) *ControlClient {
	client := container.Balance().GenerateClient(CONTROL_SERVICE, subject)
	c := &ControlClient{
		Client: client,
	}
	return c
}

func (cc *ControlClient) Join(cl ControlListen, id string) {
	socket := cluster.NewSocket(id, cl)
	cc.Client.Join(socket, id)
}
